package gz.itcast.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Created 吴海杰 on 2017/2/27.
 */

public class JdbcUtil {
       private static String url=null;
       private static  String user=null;
       private static String password=null;
       private static String driverClass=null;

    static{
        try {
        Properties props=new Properties();
        /*FileInputStream in=new FileInputStream("./src/Jdbc.properties");*/
        //使用类路径的读取方式,/：表示classpath的根目
       InputStream in=JdbcUtil.class.getResourceAsStream(
                    "/Jdbc.properties");
        props.load(in);
        url=props.getProperty("url");
        user=props.getProperty("user");
        password=props.getProperty("password");
        driverClass=props.getProperty("driverClass");
            System.out.println(url);
            System.out.println(user);
            System.out.println(password);
            System.out.println(driverClass);

        //注册驱动程序

            Class.forName(driverClass);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("驱动程序注册出错");
        }
    }
    public static Connection getConnection(){
           try {
               Connection conn= DriverManager.getConnection(url,user,password);
               return conn;
           }catch (SQLException e){
               e.printStackTrace();
               throw new RuntimeException(e);
           }
    }

    public static void close(Connection conn, Statement stmt) {
        if(stmt!=null){
            try {
                stmt.close();
            }catch (SQLException e){
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if (conn!=null){
            try {
                conn.close();
            }catch (SQLException e){
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}
